package com.mjh.zhujianju.service.party.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.github.pagehelper.PageHelper;
import com.google.common.collect.Maps;
import com.livew.framework.base.model.FileEO;
import com.livew.framework.base.model.SysUser;
import com.livew.framework.base.service.FileService;
import com.livew.framework.base.service.SysUserService;
import com.livew.framework.base.service.impl.BaseServiceImpl;
import com.livew.framework.exception.XTBusinessException;
import com.livew.framework.page.PagedBeanUtil;
import com.livew.framework.page.PagedResult;
import com.livew.framework.pojo.LoginUserInfo;
import com.livew.framework.utils.XTCurrentUser;
import com.livew.framework.utils.XTListUtils;
import com.mjh.zhujianju.dao.party.BuildingMeetingMapper;
import com.mjh.zhujianju.dao.party.BuildingMeetingUsersMapper;
import com.mjh.zhujianju.enums.BuildingMeetingEnum;
import com.mjh.zhujianju.enums.BuildingMeettingStatusEnum;
import com.mjh.zhujianju.enums.BusinessEnum;
import com.mjh.zhujianju.model.base.ContentEO;
import com.mjh.zhujianju.model.party.BuildingMeetingEO;
import com.mjh.zhujianju.model.party.BuildingMeetingUsersEO;
import com.mjh.zhujianju.service.agency.DeptUserService;
import com.mjh.zhujianju.service.base.ContentService;
import com.mjh.zhujianju.service.party.BuildingMeetingService;
import com.mjh.zhujianju.vo.agency.DeptUserVO;
import com.mjh.zhujianju.vo.base.SysUserVO;
import com.mjh.zhujianju.vo.party.BuildingMeetingUserVO;
import com.mjh.zhujianju.vo.party.BuildingMeetingVO;

@Service
public class BuildingMeetingServiceImpl extends BaseServiceImpl<BuildingMeetingEO> implements BuildingMeetingService {

    @Resource
    private BuildingMeetingMapper buildingMeetingMapper;

    @Autowired
    private BuildingMeetingUsersMapper buildingMeetingUsersMapper;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private ContentService contentService;
    
    @Resource
    private DeptUserService deptUserService;

    @Autowired
    private FileService fileService;

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

    public BuildingMeetingServiceImpl(BuildingMeetingMapper buildingMeetingMapper) {
        super(buildingMeetingMapper);
    }

    @Override
    public PagedResult<BuildingMeetingVO> findBuildingNewsPagination(BuildingMeetingEO buildingMeetingEO) {
        Integer pageNo = buildingMeetingEO.getPageNo() == null ? 1 : buildingMeetingEO.getPageNo();
        Integer pageSize = buildingMeetingEO.getPageSize() == null ? 15 : buildingMeetingEO.getPageSize();
        PageHelper.startPage(pageNo, pageSize);
        List<BuildingMeetingEO> list = buildingMeetingMapper.selectPagination(buildingMeetingEO);
        PagedResult<BuildingMeetingEO> page = PagedBeanUtil.toPagedResult(list);
        PagedResult<BuildingMeetingVO> result = new PagedResult<BuildingMeetingVO>();
        BeanUtils.copyProperties(page, result);
        return result;
    }

    @Override
    public void saveInfo(BuildingMeetingVO buildingMeetingVO) throws XTBusinessException {
        BuildingMeetingEO buildingMeetingEO = new BuildingMeetingEO();
        BeanUtils.copyProperties(buildingMeetingVO, buildingMeetingEO);
        if (StringUtils.isEmpty(buildingMeetingEO.getId())) {
            this.save(buildingMeetingEO);
            if (buildingMeetingVO.getBasicFunction() != null) {
                contentService.saveOrUpdate(BusinessEnum.TYPE_MEETING.getCode(), buildingMeetingEO.getId(), buildingMeetingEO.getBasicFunction());
            }

            if (!CollectionUtils.isEmpty(buildingMeetingVO.getUserIds())) {
                List<BuildingMeetingUsersEO> buildingMeetingUsersEOS = new ArrayList<BuildingMeetingUsersEO>();
                BuildingMeetingUsersEO buildingMeetingUsersEO = null;
                for (Long id : buildingMeetingVO.getUserIds()) {
                    buildingMeetingUsersEO = new BuildingMeetingUsersEO();
                    buildingMeetingUsersEO.setMeetingId(buildingMeetingEO.getId());
                    buildingMeetingUsersEO.setUserId(id);
                    buildingMeetingUsersEO.setIsCkeck("0");
                    buildingMeetingUsersEOS.add(buildingMeetingUsersEO);
                }


                buildingMeetingUsersMapper.insertMeetingUsers(buildingMeetingUsersEOS);
            }
        } else {
        	buildingMeetingEO.setCreateUserId(null);
            this.updateByPrimaryKeySelective(buildingMeetingEO);

            if (!CollectionUtils.isEmpty(buildingMeetingVO.getUserIds())) {
                buildingMeetingUsersMapper.delByMeetingId(buildingMeetingEO.getId());
            }

            if (!CollectionUtils.isEmpty(buildingMeetingVO.getUserIds())) {
                List<BuildingMeetingUsersEO> buildingMeetingUsersEOS = new ArrayList<BuildingMeetingUsersEO>();
                BuildingMeetingUsersEO buildingMeetingUsersEO = null;
                for (Long id : buildingMeetingVO.getUserIds()) {
                    buildingMeetingUsersEO = new BuildingMeetingUsersEO();
                    buildingMeetingUsersEO.setMeetingId(buildingMeetingEO.getId());
                    buildingMeetingUsersEO.setUserId(id);
                    buildingMeetingUsersEO.setIsCkeck("0");
                    buildingMeetingUsersEOS.add(buildingMeetingUsersEO);
                }


                buildingMeetingUsersMapper.insertMeetingUsers(buildingMeetingUsersEOS);
            }

            // 更新内容
            contentService.saveOrUpdate(BusinessEnum.TYPE_MEETING.getCode(), buildingMeetingEO.getId(), buildingMeetingEO.getBasicFunction());
        }
    }

    @Override
    public BuildingMeetingVO queryBuildingMeetingInfo(Long id) {
        //详情
        BuildingMeetingEO buildingMeetingEO = buildingMeetingMapper.selectByPrimaryKey(id);
        if (buildingMeetingEO == null) {
            return null;
        }

        BuildingMeetingVO buildingMeetingVO = new BuildingMeetingVO();
        BeanUtils.copyProperties(buildingMeetingEO, buildingMeetingVO);

        buildingMeetingVO.setBasicFunction(getContent(buildingMeetingVO.getId()));

        //处理时间
        String startTime = sdf.format(buildingMeetingVO.getStartTime());
        String endTime = sdf.format(buildingMeetingVO.getEndTime());
        buildingMeetingVO.setDateTimeStr(startTime + " 至 " + endTime);
        //处理人员
        try {
            if (buildingMeetingVO.getCreateUserId() != null) {
                SysUser sysUser = sysUserService.getByPrimaryKey(buildingMeetingVO.getCreateUserId());
                if (sysUser != null) {
                    buildingMeetingVO.setCreateUserName(sysUser.getNickname());
                }
            }
        } catch (XTBusinessException e) {
            e.printStackTrace();
        }
        //参会人员
        BuildingMeetingUsersEO buildingMeetingUsersEO = new BuildingMeetingUsersEO();
        buildingMeetingUsersEO.setMeetingId(buildingMeetingVO.getId());
        List<BuildingMeetingUsersEO> buildingMeetingUsersEOS = buildingMeetingUsersMapper.selectListByCondition(buildingMeetingUsersEO);
        List<Long> ids = buildingMeetingUsersEOS.stream().map(buildingMeetingUsersEOS1 -> buildingMeetingUsersEOS1.getUserId()).distinct().collect(Collectors.toList());
        buildingMeetingVO.setUserIds(ids);
        if (!CollectionUtils.isEmpty(ids)) {
            StringBuilder sb = new StringBuilder();
            for (Long tempId : ids) {
                sb.append(tempId);
                sb.append(",");
            }
            String tempStr = sb.toString();
            buildingMeetingVO.setUserIdStr(tempStr.substring(0, tempStr.length() - 1));
        }

        //查詢用戶照片
        if (!CollectionUtils.isEmpty(ids)) {
            List<SysUser> sysUsers = sysUserService.getSysUserByIds(ids);
            Map<Long, FileEO> files = fileService.getMapTopOne(ids, SysUser.class.getName(), null);
            if (!CollectionUtils.isEmpty(sysUsers)) {
                List<SysUserVO> sysUserVOS = new ArrayList<SysUserVO>();
                for (SysUser sysUser : sysUsers) {
                    SysUserVO sysUserVO = new SysUserVO();
                    BeanUtils.copyProperties(sysUser, sysUserVO);
                    sysUserVOS.add(sysUserVO);
                    FileEO file = files.get(sysUserVO.getId());
                    if (file != null) {
                        if (file.getId() > 0) {
                            sysUserVO.setHeadImage("/file/showImage/" + file.getId());
                        } else {
                            sysUserVO.setHeadImage("/image/defualt.png");
                        }
                    } else {
                        sysUserVO.setHeadImage("/image/defualt.png");
                    }

                    buildingMeetingVO.getSysUserVOS().add(sysUserVO);
                }
            }
        }


        return buildingMeetingVO;
    }
    
    @Override
    public BuildingMeetingVO queryAPIBuildingMeetingInfo(Long id) {
    	//详情
    	BuildingMeetingEO buildingMeetingEO = buildingMeetingMapper.selectByPrimaryKey(id);
    	if (buildingMeetingEO == null) {
    		return null;
    	}
    	
    	BuildingMeetingVO buildingMeetingVO = new BuildingMeetingVO();
    	BeanUtils.copyProperties(buildingMeetingEO, buildingMeetingVO);
    	
    	buildingMeetingVO.setBasicFunction(getContent(buildingMeetingVO.getId()));
    	
    	try {
    		SysUser user =	sysUserService.getByPrimaryKey(buildingMeetingEO.getCreateUserId());
    		if(user!=null) {
    			buildingMeetingVO.setNickname(user.getNickname());
    		}
		} catch (XTBusinessException e1) {
			e1.printStackTrace();
		}
    	//处理人员
    	try {
    		if (buildingMeetingVO.getCreateUserId() != null) {
    			SysUser sysUser = sysUserService.getByPrimaryKey(buildingMeetingVO.getCreateUserId());
    			if (sysUser != null) {
    				buildingMeetingVO.setCreateUserName(sysUser.getNickname());
    			}
    		}
    	} catch (XTBusinessException e) {
    		e.printStackTrace();
    	}
    	//参会人员
    	BuildingMeetingUsersEO buildingMeetingUsersEO = new BuildingMeetingUsersEO();
    	buildingMeetingUsersEO.setMeetingId(buildingMeetingVO.getId());
    	List<BuildingMeetingUsersEO> buildingMeetingUsersEOS = buildingMeetingUsersMapper.selectListByCondition(buildingMeetingUsersEO);
    	List<Long> ids = buildingMeetingUsersEOS.stream().map(buildingMeetingUsersEOS1 -> buildingMeetingUsersEOS1.getUserId()).distinct().collect(Collectors.toList());
    	buildingMeetingVO.setUserIds(ids);
    	if (!CollectionUtils.isEmpty(ids)) {
    		StringBuilder sb = new StringBuilder();
    		for (Long tempId : ids) {
    			sb.append(tempId);
    			sb.append(",");
    		}
    		String tempStr = sb.toString();
    		buildingMeetingVO.setUserIdStr(tempStr.substring(0, tempStr.length() - 1));
    	}
    	
    	//查詢用戶照片
    	if (!CollectionUtils.isEmpty(ids)) {
    		List<SysUser> sysUsers = sysUserService.getSysUserByIds(ids);
    		Map<Long, FileEO> files = fileService.getMapTopOne(ids, SysUser.class.getName(), null);
    		if (!CollectionUtils.isEmpty(sysUsers)) {
    			List<SysUserVO> sysUserVOS = new ArrayList<SysUserVO>();
    			for (SysUser sysUser : sysUsers) {
    				SysUserVO sysUserVO = new SysUserVO();
    				BeanUtils.copyProperties(sysUser, sysUserVO);
    				sysUserVOS.add(sysUserVO);
    				FileEO file = files.get(sysUserVO.getId());
    				if (file != null) {
    					if (file.getId() > 0) {
    						sysUserVO.setHeadImage("/file/showImage/" + file.getId());
    					} else {
    						sysUserVO.setHeadImage("/image/defualt.png");
    					}
    				} else {
    					sysUserVO.setHeadImage("/image/defualt.png");
    				}
    				
    				buildingMeetingVO.getSysUserVOS().add(sysUserVO);
    			}
    		}
    	}
    	List<BuildingMeetingVO> list =new  ArrayList<BuildingMeetingVO>();
    	list.add(buildingMeetingVO);
    	initList(list);
    	buildingMeetingVO.setqCode("/signIn/meeting/"+buildingMeetingVO.getId()+"/");
    	buildingMeetingVO.setqRCodeUrl("/file/showQCode?content=");
    	return buildingMeetingVO;
    }

    @Override
    public PagedResult<BuildingMeetingUserVO> findBuildingMeetingUsersPagination(BuildingMeetingUsersEO buildingMeetingUsersEO) {
        Integer pageNo = buildingMeetingUsersEO.getPageNo() == null ? 1 : buildingMeetingUsersEO.getPageNo();
        Integer pageSize = buildingMeetingUsersEO.getPageSize() == null ? 15 : buildingMeetingUsersEO.getPageSize();
        List<BuildingMeetingUserVO> buildingMeetingUserVOS = null;
        PageHelper.startPage(pageNo, pageSize);
        List<BuildingMeetingUsersEO> list = buildingMeetingUsersMapper.selectPagination(buildingMeetingUsersEO);
        if (!CollectionUtils.isEmpty(list)) {
            List<Long> ids = list.stream().map(buildingMeetingUsersEOS1 -> buildingMeetingUsersEOS1.getUserId()).distinct().collect(Collectors.toList());
            //查詢用戶照片
            if (!CollectionUtils.isEmpty(ids)) {
                Map<Long, FileEO> files = fileService.getMapTopOne(ids, SysUser.class.getName(), null);
                Map<Long,SysUser> sysUserMap = sysUserService.getMapTopOne(ids);
                buildingMeetingUserVOS = new ArrayList<BuildingMeetingUserVO>();
                for (BuildingMeetingUsersEO buildingMeetingUsersEO1 : list) {
                    BuildingMeetingUserVO buildingMeetingUserVO = new BuildingMeetingUserVO();
                    BeanUtils.copyProperties(buildingMeetingUsersEO1, buildingMeetingUserVO);
                    FileEO file = files.get(buildingMeetingUserVO.getId());
                    if (file != null) {
                        if (file.getId() > 0) {
                            buildingMeetingUserVO.setHeadImage("/file/showImage/" + file.getId());
                        } else {
                            buildingMeetingUserVO.setHeadImage("/image/defualt.png");
                        }
                    } else {
                        buildingMeetingUserVO.setHeadImage("/image/defualt.png");
                    }

                    buildingMeetingUserVO.setSysUser(sysUserMap.get(buildingMeetingUserVO.getUserId()));

                    buildingMeetingUserVOS.add(buildingMeetingUserVO);
                }
            }
        }

        if(!CollectionUtils.isEmpty(buildingMeetingUserVOS)){
            PagedResult<BuildingMeetingUserVO> page = PagedBeanUtil.toPagedResult(buildingMeetingUserVOS);
            return page;
        }

        return null;
    }

    private String getContent(Long id) {
        ContentEO content = contentService.queryContentByTypeAndId(BusinessEnum.TYPE_MEETING.getCode(), id);
        if (content != null) {
            return content.getContent();
        }
        return null;
    }

    @Override
    public BuildingMeetingVO getInfo(Long id) throws XTBusinessException {
        BuildingMeetingEO buildingMeetingEO = super.getByPrimaryKey(id);
        if (buildingMeetingEO != null) {
            BuildingMeetingVO vo = new BuildingMeetingVO();
            BeanUtils.copyProperties(buildingMeetingEO, vo);
            vo.setBasicFunction(getContent(id));
            return vo;
        }

        return null;
    }

    @Override
    public Map<String, List<BuildingMeetingVO>> queryBuildingMeetingList(Long userId) {
        Map<String, List<BuildingMeetingVO>> map = Maps.newHashMap();

        //查询自己创建的会议
        List<BuildingMeetingVO> meetingVOList = buildingMeetingMapper.selectMettingByUserId(userId);
        if (!CollectionUtils.isEmpty(meetingVOList)){
        	LoginUserInfo info = 	XTCurrentUser.getCurrentUser();
        	for (BuildingMeetingVO buildingMeetingVO : meetingVOList) {
        		buildingMeetingVO.setUserId(info.getId());
        		buildingMeetingVO.setDeptName(info.getDeptName());
        		buildingMeetingVO.setNickname(info.getNickname());
			}
            initList(meetingVOList);
        }
        map.put("addList",meetingVOList);

        List<BuildingMeetingUsersEO> buildingMeetingUsersEOList = buildingMeetingUsersMapper.selectMeetingUsersByUserId(userId);
        List<BuildingMeetingVO> list = null;
        if (!CollectionUtils.isEmpty(buildingMeetingUsersEOList)){
            List<Long> ids = buildingMeetingUsersEOList.stream().map(buildingMeetingUsersEO -> buildingMeetingUsersEO.getMeetingId()).distinct().collect(Collectors.toList());
            list = buildingMeetingMapper.selectMettingByIds(ids);
            Map<Long,BuildingMeetingUsersEO> meetingUsersMap = new HashMap<Long, BuildingMeetingUsersEO>();
            for (BuildingMeetingUsersEO temp : buildingMeetingUsersEOList) {
            	meetingUsersMap.put(temp.getMeetingId(), temp);
			}
            if(!XTListUtils.isEmpty(list)) {
            	List<Long > userIds = new ArrayList<>(); 
            	for (BuildingMeetingVO vo : list) {
            		userIds.add(vo.getCreateUserId());
            		if(meetingUsersMap!=null) {
            			BuildingMeetingUsersEO user= 	meetingUsersMap.get(vo.getId());
            			if(user!=null) {
            				vo.setIsCkeck(user.getIsCkeck());
            				vo.setIsCkeckName(BuildingMeetingEnum.getName(user.getIsCkeck()));
            			}
            		}
				}
            	Map<Long, SysUser>  userMap =     	sysUserService.getMapByIdList(userIds);
            	Map<Long, DeptUserVO>  deptMap =deptUserService.getDeptByUserIds(userIds);
            	if(userMap!=null) {
            		for (BuildingMeetingVO vo : list) {
            			SysUser	 user =	userMap.get(vo.getCreateUserId());
            			if(user!=null) {
            				vo.setNickname(user.getNickname());
            				vo.setUserId(user.getCreateUserId());
            			}
            			if(deptMap!=null) {
            				DeptUserVO dept =		deptMap.get(vo.getCreateUserId());
            				if(dept!=null) {
            					vo.setDeptName(dept.getDeptName());
            				}
            			}
    				}	
            	}
            }
            initList(list);
        }
        map.put("joinList",list);
        return map;
    }

    /**
     * 格式化 日期，用于前台展示所用
     * @param list
     */
    private void initList(List<BuildingMeetingVO> list){
        SimpleDateFormat sdf=new SimpleDateFormat("MM-dd");
        SimpleDateFormat sdf2=new SimpleDateFormat("HH:mm");
        Date date = new Date();
        for (BuildingMeetingVO vo : list){
            //会议开始时间
            String[] str = sdf.format(vo.getStartTime()).split("-");
            String s = str[0]+"月"+str[1]+"日";
            vo.setDateTimeStr(s);

            //会议时间段
            String total = sdf2.format(vo.getStartTime())+"-"+sdf2.format(vo.getEndTime());
            vo.setTotalTimeStr(total);

            int compareTo1 =date.compareTo(vo.getStartTime());
            int compareTo2 =date.compareTo(vo.getEndTime());
            if (compareTo1 == 1  && compareTo2 == 1){
            	vo.setMeetingStatus(BuildingMeettingStatusEnum.end.getCode());
            	vo.setMeetingStatusName(BuildingMeettingStatusEnum.end.getName());
                System.out.println("已结束");
            }else if (compareTo1 == -1 && compareTo2 == -1){
                System.out.println("未开始");
                vo.setMeetingStatus(BuildingMeettingStatusEnum.no.getCode());
                vo.setMeetingStatusName(BuildingMeettingStatusEnum.no.getName());
            }else if(compareTo1 == 1 && compareTo2 == -1){
            	vo.setMeetingStatus(BuildingMeettingStatusEnum.ing.getCode());
            	vo.setMeetingStatusName(BuildingMeettingStatusEnum.ing.getName());
                System.out.println("进行中");
            }
        }
    }

	@Override
	public void updateUsersStatus(Long meetId, Long userId) throws XTBusinessException {
		BuildingMeetingEO  metting = 	this.buildingMeetingMapper.selectByPrimaryKey(meetId);
		if(metting==null) {
			throw new XTBusinessException("无此会议");
		}
		if(metting.getEndTime()!=null&&metting.getStartTime().after(new Date())) {//结束时间
			throw new XTBusinessException("会议已结束");
		}else if(metting.getEndTime()==null&&metting.getStartTime().after(new Date())) {  //无结束时间 则用开始时间判断
			throw new XTBusinessException("会议已结束");
		}
		BuildingMeetingUsersEO eo = new BuildingMeetingUsersEO();
		eo.setMeetingId(meetId);
		eo.setUserId(userId);
		List<BuildingMeetingUsersEO>  list =	this.buildingMeetingUsersMapper.selectQianDao(eo);
		if(XTListUtils.isEmpty(list)) {
			throw new XTBusinessException("您不是参会人员");
		}
		BuildingMeetingUsersEO user =	list.get(0);
		if(BuildingMeetingEnum.SIGN.getCode().equals(user.getIsCkeck())) {
			throw new XTBusinessException("您已签到");
		}
		BuildingMeetingUsersEO user2 = new BuildingMeetingUsersEO();
		user2.setIsCkeck(BuildingMeetingEnum.SIGN.getCode());
		user2.setUpdateTime(new Date());
		user2.setId(user.getId());
		buildingMeetingUsersMapper.updateByPrimaryKeySelective(user2);
	}

    
    
    
    
}
